<?php

namespace app\admin\controller;

use app\admin\common\Constants;
use app\admin\model\Company;
use app\admin\model\RolesCache;
use app\admin\model\Staff;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class User extends \app\admin\controller\Backend
{
    protected $model = null;
    private $searchFields = ['name', 'status'];
    protected $needSelectCompany = true;
    protected $beforeActionList = [
        'getCurrentCompany',
        'permitNew' => ['only' => 'save'],
        'validateParams' => ['only' => 'add'],
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User();
    }

    public function create()
    {
        $roleModel = new RolesCache();
        $company = Company::with(['departments', 'positions'])->where(["id" => $this->company->id])->find();
        $this->assign('company', $company);
        $department = \app\admin\model\Department::where(["company_id" => $this->company->id, 'is_del' => 0])->select();
        $positions = \app\admin\model\Position::where(["company_id" => $this->company->id])->select();
        $this->assign('departments', $department);
        $roles = $roleModel->getRoles();
        $this->assign('roles', $roles);

        $this->assign('positions', $positions);
        return $this->fetch();
    }

    public function add($id = null)
    {
        $this->existModel();
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {

                $id = db('user')->where(['mobile' => $params['account']])->value('id');
                $companyId = $this->company->id;
                if ($id) {
                    //已经存在
                    $condition['uid'] = $id;
                    $condition['company_id'] = $companyId;
                    $res = db('staff')->where($condition)->find();
                    if ($res) {
                        $this->error('此员工已存在，请勿重复添加');
                    } else {
                        //这个员工虽然在用户表有，但是在这个公司不存在，添加到员工表
                        $data['uid'] = $id;
                        $data['company_id'] = $companyId;
                        $data['role'] = $params['role'];
                        $data['is_carbon'] = $params['is_carbon'];
                        $data['department_id'] = join(",", $params['department_ids']);
                        $data['position_id'] = $params['position_id'];
                        $data['create_time'] = time();
                        $userid = db('staff')->insertGetId($data);
                        if ($userid) {
                            $this->success("成功", url("user/index"));
                        } else {
                            $this->error('失败');
                        }

                    }
                } else {
                    $add_data['mobile'] = $params['account'];
                    $add_data['account'] = $params['account'];
                    $password = $params['password'] ? : '12345678';
                    $add_data['password'] = thinkEncrypt($password);
                    $add_data['username'] = $params['username'];
                    $add_data['create_time'] = time();
                    $res = db('user')->insertGetId($add_data);
                    if ($res) {
                        db('auth_group_access')->insert(['uid' => $res, 'group_id' => 1]);

                        $data['uid'] = $res;
                        $data['company_id'] = $companyId;
                        $data['role'] = $params['role'];
                        $data['is_carbon'] = $params['is_carbon'];
                        $data['department_id'] = join(",", $params['department_ids']);
                        $data['position_id'] = $params['position_id'];
                        $data['create_time'] = time();

                        $userid = db('staff')->insertGetId($data);
                        if ($userid) {
                            $this->success("成功", url("user/index"));
                        }


                    } else {
                        $this->error('失败');
                    }
                }


            }
            $this->error("参数不正确");
        }
        $this->success("添加成功", url("user/index"));
    }

    public function edit($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error('记录不存在');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $company = $this->company;
                $result = false;
                $params['company_id'] = $company->id;
                $departmentIds = $params['department_ids'];
                $positionIds = $params['position_id'];
                $roleId = $params['role_id'];
                $is_carbon = $params['is_carbon'];
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $username = $params['username'];
                    $mobile = $params['mobile'];
                    $updateUser = [];
                    if (is_null($params['username'])) {
                        $updateUser['username'] = $username;
                    }
                    if (is_null($params['mobile'])) {
                        $updateUser['mobile'] = $mobile;
                    }
                    if (sizeof($updateUser) > 0) {
                        $result = $this->model->allowField(true)->save($params, ['id' => $id]);
                        if (!$result) {
                            $this->error($this->model->getError());
                        }
                    }

                    $result = $row->allowField(true)->save($params);
                    $staffModel = new Staff();
                    $staffModel->where('uid', $row->id)->where('company_id', $company->id)
                        ->update(['department_id' => join(",", $departmentIds), 'position_id' => $positionIds, 'role' => $roleId, 'is_carbon' => $is_carbon, 'status' => $params['status']]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $userid = db('staff')->where(['uid' => $id, 'company_id' => $company->id])->value('id');
                    $info = db('auth_group_access')->where(['uid' => $userid, 'group_id' => 1])->find();
                    // if($roleId==2){
                    //     //保存成管理员
                    //     if(!$info){
                    //         db('auth_group_access')->insert(['uid'=>$userid,'group_id'=>1]);
                    //     }
                    // }else{
                    //     //保存成普通用户
                    //     if($info){
                    //         db('auth_group_access')->delete(['uid'=>$userid,'group_id'=>1]);
                    //     }
                    // }

                    $this->success("成功", url("user/index"));
                } else {
                    $this->error('未更新');
                }
            }
            $this->error('Parameter %s can not be empty');
        }
        $department = \app\admin\model\Department::where(["company_id" => $this->company->id, 'is_del' => 0])->select();
        $positions = \app\admin\model\Position::where(["company_id" => $this->company->id])->select();
        $staff = \app\admin\model\Staff::where(["company_id" => $this->company->id, 'uid' => $id])->find();

        $roleModel = new RolesCache();
        //echo '<pre>';print_r($staff);die;
        $this->assign('departments', $department);
        $this->assign('positions', $positions);
        $this->assign('companyIds', explode(',', $staff->department_id));
        $this->assign('staff', $staff);
        $this->assign('roles', $roleModel->getRoles());
        $this->view->assign("entity", $row);
        return $this->view->fetch();
    }


    /**
     * 匹配搜索用户
     * @param $account
     */
    public function search($account)
    {
        if (!$this->request->get()) {
            $this->error("访问错误");
        }
        $users = $this->model->where('account', 'like', '%' . $account . '%')
            ->where('account', 'neq', 'admin')
            ->paginate(10);
        $this->success('', null, $users);
    }

    /**
     * 重置密码
     * @param $id 用户ID
     */
    public function resetPassword($id)
    {
        if (!$this->request->isPut()) {
            $this->error("请求错误");
        }

        $result = $this->model->changePassword($id, Constants::$COMMON_PASSWORD);
        if ($this->model->getError()) {
            $this->error($this->model->getError());
        }
        if ($result) {
            $this->success("密码已重置为" . Constants::$COMMON_PASSWORD);
        } else {
            $this->error('未更新');
        }
    }

    public function index()
    {


        $params = $this->request->param();
        $company = $this->company;

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $where = [];
        if (isset($params['company_id'])) {
            $this->error("请先选择一个企业");
        }
        if (strlen($params['query']) > 0) {
            $where['a.account'] = ['like', '%' . $params['query'] . '%'];
        }
        if (strlen($params['status']) > 0) {
            $where['b.status'] = $params['status'];
        }
        // $list = $this->model
        //     ->hasWhere('companyStaff', ['company_id' => $company->id])
        //     ->where($where)
        //     ->order($sort, $order)
        //     ->paginate($limit);
        $where['b.company_id'] = $company->id;

        // $where['a.is_admin'] = array('eq', 0);
        $list = db('user')->alias('a')->join('staff b', 'a.id=b.uid', 'LEFT')->where($where)->field('a.id,a.account,a.mobile,a.username,b.department_id,b.status')->order('id desc')->paginate($limit);
        //echo "<pre>";print_r($list);die;
        foreach ($list as $k => &$v) {
            if ($v['department_id']) {
                $partment = $v['department_id'];
                $name = [];
                $partment_list = explode(',', $partment);
                foreach ($partment_list as $kk => $vv) {
                    $name[] = db('department')->where(['id' => $vv])->value('name');
                }
                $v['partment_name'] = join(",", $name);

                unset($name);
                if ($list[$k]['status'] == 1) {
                    $v['status_name'] = '正常';
                } elseif ($list[$k]['status'] == 2) {
                    $v['status_name'] = '锁定';
                } elseif ($list[$k]['status'] == 3) {
                    $v['status_name'] = '禁用';
                } else {
                    $v['status_name'] = '正常';
                }
                $list[$k] = $v;
            }
        }
        $this->assign('list', $list);
        $this->assign('params', $params);
        return $this->fetch();
    }

    public function importExcel($file)
    {
        // include(__DIR__.'/../../../ThinkPHP/Library/vendor/phpexcel/PHPExcel.php');
        vendor('phpexcel.PHPExcel');
        vendor('phpexcel.PHPExcel.IOFactory');
        $fileName = $file['image']["name"];
        $filePath = $file['image']['tmp_name'];

        $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        if ($extension == 'xlsx') {
            $objReader = new \PHPExcel_Reader_Excel2007();
            $PHPExcel = $objReader->load($filePath);
        } else if ($extension == 'xls') {
            $objReader = new \PHPExcel_Reader_Excel5();
            $PHPExcel = $objReader->load($filePath);
        } else if ($extension == 'csv') {
            $objReader = new \PHPExcel_Reader_CSV();
            $PHPExcel = $objReader->load($filePath);
        }


        $sheet = $PHPExcel->getSheet(0); //获取指定的sheet表

        $rows = $sheet->getHighestRow();   //行数
        $cols = $sheet->getHighestColumn();//列数
        $data = array();
        for ($i = 1; $i <= $rows; $i++) { //行数是以第1行开始
            $count = 0;
            for ($j = 'A'; $j <= $cols; $j++) { //列数是以A列开始
                $value = $sheet->getCell($j . $i)->getValue();

                $data[$i - 1][$count] = (string)$sheet->getCell($j . $i)->getValue();
                $count += 1;

            }
        }
        return $data;
    }


    //导入
    public function import()
    {
        //接收上传文件
        $file = $_FILES;
        if (!$file) {
            $this->error('缺少file');
        }
        $company = $this->company;
        $company_id = $company->id;
        //调用导入excel方法
        $data = $this->importExcel($file);
        //print_r($data);die;
        $sql = [];
        $staff_sql = [];
        for ($i = 1; $i < count($data); $i++) {
            $mobile = $data[$i][0];
            $sql['mobile'] = $data[$i][0];
            $sql['username'] = $data[$i][1];
            $sql['password'] = thinkEncrypt(12345678);
            $sql['account'] = $data[$i][0];
            $staff_sql['department_id'] = $data[$i][2];
            $staff_sql['position_id'] = $data[$i][3];
            $staff_sql['role'] = $data[$i][4];
            $staff_sql['company_id'] = $company_id;
            $staff_sql['create_time'] = time();

            $id = db('user')->where(['mobile' => $mobile])->value('id');
            if ($id) {
                //已经存在
                $condition['uid'] = $id;
                $condition['company_id'] = $company_id;
                $re = db('staff')->where($condition)->find();
                if ($re) {
                    //apiReturn(2,'此员工已存在，请勿重复添加',$res);
                } else {
                    //这个员工虽然在用户表有，但是在这个公司不存在，添加到员工表
                    $staff_sql['uid'] = $id;
                    $res = db('staff')->insert($staff_sql);

                }
            } else {
                $sql['create_time'] = time();
                $re = db('user')->insertGetId($sql);
                if ($re) {
                    db('auth_group_access')->insert(['uid' => $re, 'group_id' => 1]);
                    $staff_sql['uid'] = $re;
                    $res = db('staff')->insertGetId($staff_sql);
                }
            }
        }

        if ($res) {
            $value = ['code' => '1', 'msg' => '成功'];
            exit(json_encode($value));
        } else {
            $value = ['code' => '1', 'msg' => '失败'];
            exit(json_encode($value));
        }
    }


    public function dc28()
    {
        vendor('phpexcel.PHPExcel');

        $company = $this->company;
        $company_id = $company->id;
        $list = db('department')->where(['company_id' => $company_id])->select();

        foreach ($list as $k => $v) {
            $name .= ',' . $v['id'] . ':' . $v['name'];
        }
        $name = substr($name, 1);

        $position_list = db('position')->where(['company_id' => $company_id])->select();
        foreach ($position_list as $k => $v) {
            $position_name .= ',' . $v['id'] . ':' . $v['name'];
        }
        $position_name = substr($position_name, 1);
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '手机号码')
            ->setCellValue('B1', '姓名')
            ->setCellValue('C1', '部门' . $name)
            ->setCellValue('D1', '职位' . $position_name)
            ->setCellValue('E1', '角色(1:普通用户 2：管理员)');

        //设置A列水平居中
        // $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()->getHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置单元格宽度
        //6.循环刚取出来的数组，将数据逐一添加到excel表格。
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(80);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(80);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(40);

        //7.设置保存的Excel表格名称
        $filename = 'yz' . date('ymd', time()) . '.xls';
        //8.设置当前激活的sheet表格名称；
        $objPHPExcel->getActiveSheet()->setTitle('cs');
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $filename . '"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;


    }


    public function dc()
    {
        $params = $this->request->param();
        $company = $this->company;

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $where = [];
        if (isset($params['company_id'])) {
            $this->error("请先选择一个企业");
        }
        if (strlen($params['query']) > 0) {
            $where['a.account'] = ['like', '%' . $params['query'] . '%'];
        }
        if (strlen($params['status']) > 0) {
            $where['b.status'] = $params['status'];
        }
        // $list = $this->model
        //     ->hasWhere('companyStaff', ['company_id' => $company->id])
        //     ->where($where)
        //     ->order($sort, $order)
        //     ->paginate($limit);
        $where['b.company_id'] = $company->id;

        // $where['a.is_admin'] = array('eq', 0);
        $list = db('user')->alias('a')->join('staff b', 'a.id=b.uid', 'LEFT')->where($where)->field('a.id,a.account,a.mobile,a.username,b.department_id,b.status')->order('id desc')->select();
        foreach ($list as $k => &$v) {
            if ($v['department_id']) {
                $partment = $v['department_id'];
                $name = [];
                $partment_list = explode(',', $partment);
                foreach ($partment_list as $kk => $vv) {
                    $name[] = db('department')->where(['id' => $vv])->value('name');
                }
                $v['partment_name'] = join(",", $name);

                unset($name);
                if ($list[$k]['status'] == 1) {
                    $v['status_name'] = '正常';
                } elseif ($list[$k]['status'] == 2) {
                    $v['status_name'] = '锁定';
                } elseif ($list[$k]['status'] == 3) {
                    $v['status_name'] = '禁用';
                } else {
                    $v['status_name'] = '正常';
                }
                $list[$k] = $v;
            }
        }

        vendor('phpexcel/PHPExcel');
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //exit($objPHPExcel);
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'UID')
            ->setCellValue('B1', '账号')
            ->setCellValue('C1', '昵称')
            ->setCellValue('D1', '手机号码')
            ->setCellValue('E1', '状态');

        //设置A列水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置单元格宽度
        //6.循环刚取出来的数组，将数据逐一添加到excel表格。
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(20);


        for ($i = 0; $i < count($list); $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $list[$i]['id']);         //ID
            $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $list[$i]['account']);    //标签码
            $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $list[$i]['username']);   //防伪码
            $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $list[$i]['mobile']);     //ID
            $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $list[$i]['status_name']);//标签码
        }
        //7.设置保存的Excel表格名称
        $filename = 'yz' . date('ymd', time()) . '.xls';
        //8.设置当前激活的sheet表格名称；
        $objPHPExcel->getActiveSheet()->setTitle('cs');
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $filename . '"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;


    }

    /**
     * 删除关联信息
     * @param $id
     */
    public function delete($id)
    {
        $error = '';
        if ($id <= 0) {
            $error .= '参数传递错误[' . $id . ']！<br>';
        }
        $map = ['uid' => $id, 'company_id' => $this->company->id];
        $staffModel = new Staff();
        try {
            Db::startTrans();
            $staffModel->where($map)->delete();
            Db::commit();
        } catch (Exception $e) {
            $error .= $e->getMessage();
        }
        if ($error) {
            $this->error($error);
        }
        $this->success('删除成功');
    }

    protected function validateParams()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            if (count($params['department_ids']) <= 0) {
                $this->error('请选择部门');
            }
            if ($this->request->post('position_id', '') == '') {
                $this->error('请选择职位');
            }
        }
    }

    /**
     * 检测输入参数
     */
    protected function permitNew()
    {
        $data = $this->request->param();
        if (empty($data['password'])) {
            $this->error('密码不能为空');
        }
        if ($data['password'] != $data['password_confirm']) {
            $this->error('两次输入的密码不一致');
        }
        if (empty($data['username'])) {
            $this->error('用户名不能为空');
        }
        if (empty($data['mobile'])) {
            $this->error('手机号不能为空');
        }
        if (empty($data['role_id'])) {
            $this->error('请选择角色');
        }
    }

}